package com.macoli.dynamicmockserver.converter

import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import org.json.JSONObject
import retrofit2.Converter
import retrofit2.Retrofit
import java.lang.reflect.ParameterizedType
import java.lang.reflect.Type

class MapConverterFactory : Converter.Factory() {
    override fun requestBodyConverter(
        type: Type?,
        parameterAnnotations: Array<Annotation?>?,
        methodAnnotations: Array<Annotation?>?,
        retrofit: Retrofit?
    ): Converter<*, RequestBody?>? {
        if ((type as ParameterizedType).rawType == Map::class.java) {
            return MapConverter()
        }
        return null
    }

    class MapConverter : Converter<Map<String , String> , RequestBody?> {

        override fun convert(value: Map<String, String>): RequestBody? {
            val rootObj = JSONObject(value)
            return rootObj.toString().toRequestBody()
        }
    }
}